package com.sun.StudentInfo.service.impl;

import com.sun.StudentInfo.mapper.CourseMapper;
import com.sun.StudentInfo.mapper.SelectCourseMapper;
import com.sun.StudentInfo.pojo.Course;
import com.sun.StudentInfo.pojo.SC;
import com.sun.StudentInfo.pojo.Vo.CourseVo;
import com.sun.StudentInfo.service.CourseService;
import com.sun.StudentInfo.utils.CourseSelectUtils;
import com.sun.StudentInfo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class CourseServiceImpl implements CourseService {
    private static final String DEFAULT_KEY_PREFIX = "default_chosen_num_";
    private static final String KEY_PREFIX = "chosen_num_";
    private static final String COURSE_PREFIX = "course_prefix_";
    private static final String DEFAULT_VALUE = "default_value";

    @Resource
    RedisUtil redisUtil;

    @Resource
    CourseSelectUtils courseSelectUtils;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private SelectCourseMapper selectCourseMapper;

    /**
     *  添加课程
     * @param course   课程信息
     * @return  插入结果 !=0则插入成功
     */
    @Override
    public int insertCourse(Course course) {
        return courseMapper.insertCourse(course);
    }

    /**
     *  根据课程编号删除课程信息信息
     * @param cid   课程编号
     * @return  删除结果，!=0则删除成功
     */
    @Override
    public int deleteCourse(String cid) {
        return courseMapper.deleteCourse(cid);
    }

    /**
     *  修改课程信息
     * @param course   课程信息
     * @return  修改结果 !=0则修改成功
     */
    @Override
    public int modifyCourse(Course course) {
        return courseMapper.modifyCourse(course);
    }

    /**
     *  根据课程编号查询出课程实体
     * @param cid
     * @return
     */
    @Override
    public Course getByCouCid(String cid) {
        return courseMapper.getByCouCid(cid);
    }

    /**
     * 查询全部课程，接住sql语句进行分页
     * @param professionId 专业id
     * @param searchType 搜索类型
     * @param value 输入值
     * @param courseType 选修类型
     * @return 查询结果
     */
    @Override
    public List<CourseVo> selectCourseByStu(String sid, String professionId, String searchType, String value, String courseType) {
        // 如果professionId为空，则返回空
        if (StringUtils.isEmpty(professionId)) {
            return null;
        }

        Map<String,Object> data = new HashMap<>();
        data.put("courseType", courseType);
        data.put("professionId", professionId);

        // 为不同类型的查询条件赋值
        if ("cId".equalsIgnoreCase(searchType)) {
            data.put("cId", value);
        } else if ("cName".equalsIgnoreCase(searchType)) {
            data.put("cName", value);
        } else if ("tName".equalsIgnoreCase(searchType)) {
            data.put("tName", value);
        }
        List<CourseVo> courseVos = courseMapper.selectCourses(data);
        System.err.println("first course:" + courseVos);

        // 查询学生已选的课程
        Map<String,Object> querySCData = new HashMap<>();
        querySCData.put("sid",sid);
        List<SC> scList = selectCourseMapper.getSelectCourseBySid(querySCData);

        // 获取课程id的集合
        List<String> cidList = new ArrayList<>();
        if (scList != null && scList.size() > 0) {
            cidList = scList
                .stream() // 将集合转换成stream流
                .map(SC::getCid) // SC::getCid 方法引用，获取cid字段， map：提取对应字段
                .collect(Collectors.toList()); // 将map到的字段转换成集合
        }



        if (courseVos.size() > 0) {
            for (CourseVo courseVo : courseVos) {
                // 1.对课程类型赋值。这些课程对于该登录的学生而言，要么必修要么是选修
                if (!StringUtils.isEmpty(courseVo.getRequiredPro())) {
                    // 学生专业id在课程必修的专业中的索引，如果不存在，则返回-1
                    int index = courseVo.getRequiredPro().indexOf(professionId);
                    if (index >= 0) {
                        courseVo.setType("必修");
                    } else {
                        courseVo.setType("选修");
                    }
                } else {
                    courseVo.setType("选修");
                }

                // 2.是否已选该课程
                if (cidList.contains(courseVo.getCId())) {
                    // 如何已经课程的集合包含该课程id，就将HaveSelected字段设置为true，默认为false
                    courseVo.setHaveSelected(1);
                }

                // 3.设置上课安排
//                StringBuilder courseWeekSb = new StringBuilder();
//                //3.1解析上课周数
//                String courseWeek = courseVo.getCourseWeek();
//                String[] weekArray = courseWeek.split(",");
//                for (String week : weekArray) {
//                    courseWeekSb.append("第").append(week).append("周").append("，");
//                }
//                courseWeekSb.deleteCharAt(courseWeekSb.length()-1);
//                courseVo.setCourseWeek(courseWeekSb.toString());
//
//                //3.2解析上课时间
//                StringBuilder courseTimeSb = new StringBuilder();
//                String courseTime = courseVo.getCourseTime();
//                String[] timeArray = courseTime.split(",");
//                for (String time : timeArray) {
//                    String[] weekAndSectionArray = time.split(":");
//                    String weekNum = weekAndSectionArray[0]; //周几
//                    String week = parseWeek(weekNum);
//                    String section = weekAndSectionArray[1]; //第几节课
//                    courseTimeSb.append("周").append(week).append("：").append(section).append("节，");
//                }
//                courseTimeSb.deleteCharAt(courseTimeSb.length()-1);
//                courseVo.setCourseTime(courseTimeSb.toString());

                // 4.给已选人数赋值
                // 1.省一次数据库查询，提升性能
                int selectedNum = courseSelectUtils.getSelectedNum(courseVo.getCId());
                courseVo.setSelectedNum(selectedNum);
            }
        }
        return courseVos;
    }

    private String parseWeek(String weekNum) {
        switch (weekNum) {
            case "1":
                return "一";
            case "2":
                return "二";
            case "3":
                return "三";
            case "4":
                return "四";
            case "5":
                return "五";
            case "6":
                return "六";
            case "7":
                return "日";
        }
        return "";
    }

    @Override
    public int querySelectedCourseNum(String cid) {
        return courseMapper.querySelectedCourseNum(cid);
    }

    @Override
    public List<Course> selectTeacherCourses(String searchType, String value) {
        Map<String,Object> data = new HashMap<>();

        // 为不同类型的查询条件赋值
        if ("cId".equalsIgnoreCase(searchType)) {
            data.put("cId", value);
        } else if ("cName".equalsIgnoreCase(searchType)) {
            data.put("cName", value);
        } else if ("pro".equalsIgnoreCase(searchType)) {
            data.put("pro", value);
        }
        return courseMapper.selectCourseNoTeacher(data);
    }

}
